const connection = require("../db");
const jwt = require("jsonwebtoken");
const jwtConfig = require("../data/jwt");

const loginSys = (req, res, next) => {
  const sql = "SELECT * FROM tb_user where username = ? AND password = ?";
  console.log("🚀 ~ getUsers ~ req.body:", req.body);
  const { username, password } = req.body;
  connection.query(sql, [username, password], (err, result) => {
    if (err) return res.status(500).json({ success: false, error: err });
    //登录成功之后，生成jwt字符串,并通过token的形式返回给客户端
    //参数:用户的信息对象，加密的秘钥，配置的对象(当前token的有效期 30s | 2h)
    const token = jwt.sign({ username: username }, jwtConfig.jwtSecret, {
      expiresIn: "0.5h",
    });
    return res.status(200).json({
      success: true,
      token,
      message: "登录成功",
    });
  });
};

const logoutSys = (req, res, next) => {
  var addSql = "INSERT INTO tb_token(tokenName) VALUES(?)";
  const auth = req.auth;
  console.log("🚀 ~ logoutSys ~ auth:", auth);
  // connection.query(addSql, [username], (err, result) => {
  //   if (err) return res.status(500).json({ success: false, error: err });
  //   return res.status(200).json({
  //     success: true,
  //     username,
  //     message: "登录成功",
  //   });
  // });
  return res.status(200).json({
    success: true,
    auth,
    message: "登录成功",
  });
};

module.exports = { loginSys, logoutSys };
